<template>
	<div class="main-home">
		<!--				<h2>role</h2>-->
		<div class="main-search">
			<el-form :model="data.searchForm" label-width="auto" inline style="text-align: left;">
				<el-form-item label="角色名称">
					<el-input v-model="data.searchForm.roleName" clearable style="width: 250px"
					          @blur="handleSearchClick"/>
				</el-form-item>
				<!--
									<el-form-item label="状态">
										<el-select v-model="data.searchForm.deptState" clearable placeholder="&#45;&#45;请选择&#45;&#45;"
												   style="width: 240px">
											<el-option label="正常" value="0"/>
											<el-option label="禁用" value="1"/>
										</el-select>
									</el-form-item>
				-->
				<el-form-item label="">
					<el-button icon="Search" type="primary" @click="handleSearchClick" round plain>搜索</el-button>
					<el-button icon="Refresh" @click="resetSearchClick" round plain>重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!--有数据-->
		<div>
			<!--数据列表-->
			<div class="main-content">
				<h2 style="margin-bottom: 2vw">角色列表</h2>
				<div class="main-content-btn">
					<el-button type="primary" @click="handleAddClick()">新增角色</el-button>
					<el-popconfirm class="box-item" width="450"
					               title="这将选中菜单删除，确定继续？【删除后将无法恢复，请谨慎操作】"
					               icon="" placement="top" confirm-button-type="danger" confirm-button-text="删除"
					               @confirm="handleDeleteList()" persistent>
						<template #reference>
							<el-button type="danger">批量删除</el-button>
						</template>
						<template #actions="{ confirm, cancel }">
							<div class="btn-group" style="text-align: center">
								<el-button size="small" @click="cancel">取消</el-button>
								<el-button type="danger" size="small" @click="confirm">删除</el-button>
							</div>
						</template>
					</el-popconfirm>
				</div>
				<el-table :data="data.list" @selection-change="handleDeleteListClick" highlight-current-row stripe
				          style="width: 100%;">
					<el-table-column type="selection" width="55"/>
					<el-table-column prop="roleName" label="角色名称" width="150" sortable/>
					<el-table-column prop="roleType" label="角色类型" width="120">
						<template #default="scope">
							<el-tag v-if="scope.row.roleType===roleType[0].name" type="primary" effect="plain"
							        disable-transitions>
								超级管理员
							</el-tag>
							<el-tag v-else-if="scope.row.roleType===roleType[1].name" type="warning" effect="plain"
							        disable-transitions>管理员
							</el-tag>
							<el-tag v-else-if="scope.row.roleType===roleType[2].name" type="danger" effect="plain"
							        disable-transitions>普通用户
							</el-tag>
							<el-tag v-else type="danger" disable-transitions>按钮</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="permissions" label="角色权限" width="80" align="center"/>
					<el-table-column prop="remark" label="角色描述" width="180" align="center" show-overflow-tooltip/>
					<el-table-column prop="createBy" label="创建人" width="180" align="center"/>
					<el-table-column prop="createTime" label="创建时间" width="200" sortable align="center"/>
					<el-table-column prop="updateTime" label="更新时间" width="200" sortable align="center"/>
					<el-table-column label="操作" align="center" width="150" fixed="right">
						<template #default="scope">
							<div style="text-align: center">
								<el-button size="small" type="warning" plain
								           @click="handleEditClick(scope.$index, scope.row)">编辑
								</el-button>
								<el-popconfirm class="box-item" width="180"
								               :title="'确定删除 【'+scope.row.roleName+'】 ？'"
								               icon="" placement="top" confirm-button-type="danger"
								               confirm-button-text="删除"
								               @confirm="handleDelete(scope.$index, scope.row)"
								               persistent>
									<template #reference>
										<!--									@click="handleDelete(scope.$index, scope.row)"-->
										<el-button size="small" type="danger" plain>删除</el-button>
									</template>
									<template #actions="{ confirm, cancel }">
										<div class="btn-group" style="text-align: center">
											<el-button size="small" @click="cancel">取消</el-button>
											<el-button type="danger" size="small" @click="confirm">删除</el-button>
										</div>
									</template>
								</el-popconfirm>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
			
			<!--新增/修改 对话框-->
			<div class="main-dialog">
				<el-dialog v-model="data.dialog.visible" :title="data.dialog.title" center align-center draggable
				           overflow :show-close="false" width="40vw" @open="handleDialogOpened"
				           :before-close="handleClose">
					<div class="dialog-wrap" style="margin: 20px">
						<el-form :model="data.editForm">
							<el-form-item :label="data.dialog.name" label-width="100">
								<el-input v-model="data.editForm.roleName"/>
							</el-form-item>
							<el-form-item label="角色类型" label-width="100">
								<el-select v-model="data.editForm.roleType" placeholder="-- 请选择 --" size="large"
								           style="width: 100%">
									<el-option v-for="item in data.roleList" :key="item.value" :label="item.label"
									           :value="item.value"/>
								</el-select>
							</el-form-item>
							<el-form-item label="角色权限" label-width="100">
								<el-input v-model="data.editForm.permissions"/>
							</el-form-item>
							<el-form-item label="备注" label-width="100">
								<el-input v-model="data.editForm.remark"
								          type="textarea" :autosize="{ minRows: 4, maxRows: 8 }"/>
							</el-form-item>
							<el-form-item label="菜单权限" label-width="100">
								<el-tree ref="treeRef" style="width: 100%; background-color: #E8E8E8"
								         :data="data.menuList"
								         node-key="menuId"
								         :props="defaultProps" show-checkbox accordion
								         @check="handleCheckChange"/>
							</el-form-item>
						</el-form>
					</div>
					<template #footer>
						<div class="dialog-footer">
							<el-button @click="handleClose()" style="margin-right: 5vw">取消</el-button>
							<el-button v-if="data.dialog.btnName=='新增'" type="primary"
							           @click="addData">新增
							</el-button>
							<el-button v-else type="warning" @click="editData">编辑
							</el-button>
						</div>
					</template>
				</el-dialog>
				<!--删除 对话框-->
				<el-dialog v-model="data.deleteDialog.visible" title="警告" center align-center draggable overflow
				           :show-close="false" width="30vw" :before-close="handleDeleteClose">
					<h3 style="color: red; text-align: center;">该操作会删除【{{ data.deleteDialog.deleteName }}】下的所有数据！<br>请谨慎操作！<br>
					</h3>
					<p style="text-align: center; margin:3vh auto 5vh auto">是否继续？</p>
					<div class="dialog-footer" style="text-align: center">
						<el-button @click="data.deleteDialog.visible=false; infoMessage(true,'已取消')"
						           style="margin-right: 5vw">取消
						</el-button>
						<el-button type="danger" @click="data.deleteDialog.visible=false; handleDeleteForTreeId()">删除
						</el-button>
					</div>
				</el-dialog>
			</div>
		</div>
		<!--空状态-->
		<div v-if="false" class="main-content">
			<el-button type="primary" @click="handleAddClick()">新增菜单</el-button>
			<el-empty description="无数据"/>
		</div>
	</div>
</template>

<script setup lang="ts">
import { reqList, reqAdd, reqDelete, reqDeleteList, reqEdit } from '@/service/main/role.ts'
import { errorMessage, infoMessage, successMessage } from '@/utils/ElMessageUtils.ts'
import { reactive, ref } from 'vue'
import { reqMenuList } from '@/service/main/menu.ts'

/********************************************* 变量区 ************************************************************/
// 菜单权限树。
const defaultProps = {
	children: 'children',
	label: 'menuName'
}
const treeRef = ref()

// 角色类型
const roleType = [
	{ code: '0', name: 'SUPER_ADMIN' },
	{ code: '1', name: 'ADMIN' },
	{ code: '2', name: 'USER' }
]

// 数据内容。
let data = reactive({
	dialog: {
		visible: false,
		title: '新增角色',
		isAdd: false,   // 是否添加角色。
		name: '',// 角色名称
		btnName: ''
	},
	deleteDialog: {
		visible: false,
		deptId: '',
		deleteName: ''
	},
	// 搜索条件。
	searchForm: {},
	// 添加/编辑表单。
	editForm: {},
	deleteList: [],
	// 列表展示内容。
	list: [],
	// 菜单列表。
	menuList: [],
	// 角色列表。
	roleList: [{
		value: 'SUPER_ADMIN',
		label: '超级管理员'
	}, {
		value: 'ADMIN',
		label: '管理员'
	}, {
		value: 'USER',
		label: '普通用户'
	}]
})

/********************************************* API接口 ************************************************************/
// 获取数据。
const dataList = function getDataList(searchData = null) {
	reqList(searchData).then(res => {
		console.log('reqList.res ====> ', res)
		if (res.resultStatus) {
			data.list = res.resultData
		} else {
			errorMessage(true, '动态菜单获取失败！！l')
		}
	})
}
dataList()

// 获取菜单列表。
const getList = function getList(searchData = null) {
	reqMenuList(searchData).then(res => {
		console.log('reqMenuList.res ====> ', res)
		if (res.resultStatus) {
			data.menuList = res.resultData
		} else {
			errorMessage(true, '动态菜单获取失败！！l')
		}
	})
}
getList()

// 搜索框。
function handleSearchClick() {
	dataList(data.searchForm)
}

// 添加数据。
function addData() {
	data.editForm.menuPermissions = getCheckedKeys()
	// console.log('getCheckedKeys()  ====> ', getCheckedKeys())
	// console.log('data.editForm ====> ', data.editForm)
	reqAdd(data.editForm).then(res => {
		if (res.resultStatus) {
			console.log('reqAdd.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
			data.dialog.visible = false
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
	// handleSearchClick()
}

// 修改数据。
function editData() {
	data.editForm.menuPermissions = getCheckedKeys()
	reqEdit(data.editForm).then(res => {
		if (res.resultStatus) {
			console.log('reqEdit.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
			data.dialog.visible = false
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
}

/**
 * 单条删除。
 * @param type
 * @param index
 * @param row
 */
function handleDelete(index, row) {
	console.log('handleDelete.row =====>  ', row)
	reqDelete(row.roleId).then(res => {
		if (res.resultStatus) {
			console.log('reqDelete.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
}

// 批量删除。
function handleDeleteList() {
	let idList = {
		idList: []
	}
	data.deleteList.forEach((item) => {
		console.log('item ====>', item)
		idList.idList.push(item.roleId)
	})
	// console.log("ids =====>",ids)
	reqDeleteList(idList).then(res => {
		if (res.resultStatus) {
			console.log('reqDeleteList.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
}

/********************************************* 事件 ************************************************************/

// 重置搜索框。
function resetSearchClick() {
	data.searchForm = {}
}

/**
 * 添加 角色。
 * @param type
 * @param index
 * @param row
 */
function handleAddClick() {
	data.dialog = {
		visible: true,
		title: '新增角色',
		isAdd: true,
		name: '角色名称',
		btnName: '新增'
	}
}

/**
 * 编辑 角色。
 * @param type
 * @param index
 * @param row
 */
function handleEditClick(index = null, row) {
	data.dialog = {
		visible: true,
		title: '编辑角色',
		isAdd: true,
		name: '角色名称',
		btnName: '编辑'
	}
	console.log('row =====> ', row)
	// 遍历选择。
	data.editForm = row
}

/**
 * 批量删除。
 */
function handleDeleteListClick(newSelection) {
	data.deleteList = newSelection
	console.log('newSelection ====>', newSelection)
	console.log('批量删除！')
}

// 选择选中。
const handleCheckChange = (data, selectData) => {
	// console.log('selectData.checkedKeys ====> ', selectData.checkedKeys)
	setCheckedKeys(selectData.checkedKeys)
}

// 弹窗显示后，显示选中的菜单权限。
const handleDialogOpened = () => {
	// console.log('data.editForm.menuPermissions  ==> ', data.editForm.menuPermissions)
	if (data.editForm.menuPermissions) {
		setCheckedKeys(data.editForm.menuPermissions)
	}
}


/********************************************* tree选中数据 ************************************************************/
// 设置值。
const setCheckedKeys = (data) => {
	treeRef.value!.setCheckedKeys(data, false)
}
const getCheckedKeys = () => {
	return treeRef.value!.getCheckedKeys(false)
}
// 重置值。
const resetChecked = () => {
	if (treeRef.value) {
		treeRef.value!.setCheckedKeys([], false)
	}
}

/********************************************* 初始化数据 ************************************************************/
// 清除垃圾数据。
function formClear() {
	data.editForm = {}
	data.dialog = {
		visible: false,
		title: '',
		isAdd: false,
		name: '',
		btnName: '新增'
	}
	resetChecked()
}

// 关闭新增/修改弹窗。
function handleClose() {
	formClear()
	infoMessage(true, '已取消')
}

// 关闭删除弹窗。
function handleDeleteClose() {
	data.deleteDialog.visible = false
	infoMessage(true, '已取消')
}
</script>

<style scoped lang="less">
.main-search {
	background-color: white;
	margin-bottom: 20px;
	padding: 5vh 0 2vh 5vw;
	border-radius: 10px;
}

.main-content {
	background-color: white;
	padding: 20px;
	border-radius: 10px;
}

.main-content-btn {
	margin-bottom: 20px;
}

:global(.el-popconfirm__main) {
	color: red;
	text-align: center;
	white-space: pre-line;
}


.icon-list {
	display: inline-block;
	width: 35px;
	height: 35px;
}

.select-option {
	display: inline-block;
}
</style>